# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from odoo import models, fields, api
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare
from odoo.osv import orm
from odoo.tools.translate import _
from odoo.exceptions import ValidationError


class mrp_bom(models.Model):
    """
    Defines bills of material for a product.
    """
    _inherit = 'mrp.bom'

    for_fee = fields.Boolean(u'允许委外',default=False)
    fee_product_id = fields.Many2one('product.product',u'委外服务',domain="[('type', '=', 'service')]")



class mrp_production(models.Model):

    _inherit = 'mrp.production'

    @api.depends('procurement_id')
    def _get_purchase_order(self):
        result = {}
        for rec in self.browse(self.ids):
            rec.fee_purchase_order_id = rec.procurement_id.purchase_line_id.order_id.name
            rec.fee_purchase_order_line_id = rec.procurement_id.purchase_line_id.id
            # result[rec.id] = (rec.procurement_id.purchase_line_id.order_id.id)
        # return result

    procurement_id= fields.Many2one('procurement.order', 'Procurement', ondelete='set null', copy=False)
    fee_purchase_order_id = fields.Char(compute='_get_purchase_order', string=u'采购单')
    fee_purchase_order_line_id = fields.Many2one('purchase.order.line',compute='_get_purchase_order',store=True, string=u'采购单明细')

    @api.multi
    def _prepare_procurement_from_mrp(self, mrp_production=None):
        origin = mrp_production.name
        group_id = False
        location_id = False
        loc_obj = self.env["stock.location"]
        rule_obj = self.env["procurement.rule"]
        try:
            location_model, location_id = self.env['ir.model.data'].get_object_reference('stock', 'stock_location_stock')
        except (orm.except_orm, ValueError):
            location_id = False

        location = loc_obj.browse(location_id)
        wh = loc_obj.get_warehouse()

        rule = rule_obj.search([('action','=','buy')])[0]
        return {
            'name': mrp_production.name,
            'origin': mrp_production.name,
            'company_id': mrp_production.company_id and mrp_production.company_id.id or False,
            'date_planned': mrp_production.date_planned_start,
            'product_id': mrp_production.bom_id.fee_product_id.id,
            'product_qty': mrp_production.product_qty,
            'product_uom': mrp_production.bom_id.fee_product_id.uom_id.id,
            'product_uos_qty': mrp_production.product_qty,
            'product_uos': mrp_production.bom_id.fee_product_id.uom_id.id,
            'location_id': location_id,
            # 'move_dest_id': mrp_production.id,
            'move_dest_id': None,
            'group_id': group_id,
            'rule_id': rule.id,
            'route_ids': None,
            # 'route_ids': [(4, x.id) for x in mrp_production.route_ids],
            'warehouse_id': wh,
            'priority': '1',
        }

    @api.multi
    def _create_procurement(self, mrp_production):
        """ This will create a procurement order """
        vals = self._prepare_procurement_from_mrp(mrp_production)
        return self.env["procurement.order"].create(vals)


    @api.multi
    def action_assign(self):
    # def action_confirm(self):
        res = super(mrp_production,self).action_assign()
        if self.picking_type_id.outsource_type:
        # if self.production_id.picking_type_id.outsource_type:
            for production in self.browse(self.ids):
                if not production.procurement_id and production.bom_id.for_fee and production.bom_id.fee_product_id:
                    procurement_id = self._create_procurement( production)
                    production.procurement_id = procurement_id.id
        return res

    @api.multi
    def post_inventory(self):
        quantity=0
        for quantity_move in self.move_finished_ids:
            if quantity_move.product_id==self.product_id and quantity_move.state in ('confirmed','assigned'):
                quantity=quantity_move.quantity_done
        if self.picking_type_id.outsource_type and quantity>0:
            if self.procurement_id:
            # if self.fee_purchase_order_line_id:
                if not self.procurement_id.purchase_line_id:
                # if not self.fee_purchase_order_line_id:
                    raise ValidationError(u'委外服务没有生成采购单!不允许完成生产')
                if not self.procurement_id.purchase_line_id.order_id.state <> 'done':
                # if not self.fee_purchase_order_line_id.order_id.state <> 'done':
                    raise ValidationError(u'没有生成采购单!不允许完成生产')
                self.procurement_id.purchase_line_id.qty_received += quantity
                # self.fee_purchase_order_line_id.qty_received += quantity
            else:
                raise ValidationError(u'委外类型的生产单,没有服务需求,不允许完成生产')
        return super(mrp_production, self).post_inventory()

# class MrpProductProduce(models.TransientModel):
#     _inherit = "mrp.product.produce"

    # @api.multi
    # def do_produce(self):
    #     quantity = self.product_qty
    #     if self.production_id.picking_type_id.outsource_type:
    #         if self.production_id.procurement_id:
    #             if not self.production_id.procurement_id.purchase_line_id:
    #                 raise ValidationError(u'委外服务没有生成采购单!不允许完成生产')
    #             if not self.production_id.procurement_id.purchase_line_id.order_id.state<>'done':
    #                 raise ValidationError(u'没有生成采购单!不允许完成生产')
    #             self.production_id.procurement_id.purchase_line_id.qty_received +=quantity
    #         else:
    #             raise ValidationError(u'委外类型的生产单,没有服务需求,不允许完成生产')
    #     return super(MrpProductProduce,self).do_produce()

